package com.guigu.tms.security.controller;

import com.guigu.tms.commons.order.entity.vo.Result;
import com.guigu.tms.commons.user.entity.Member;
import com.guigu.tms.commons.user.feign.UserFeignClient;
import com.guigu.tms.security.service.ICustomerLoginService;
import com.guigu.tms.security.service.impl.CustomerLoginService;
import com.guigu.tms.security.service.impl.ValidateCodeServiceImpl;
import com.guigu.tms.security.util.JwtUtils;
import io.jsonwebtoken.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@RestController
@RequestMapping("/customer")
public class CustomerAuthController {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private ICustomerLoginService customerLoginService;

    @Autowired(required = false)
    private UserFeignClient userFeignClient;


    @PostMapping("login")
    public Result login(String phone, String value){
        Result result =null;
        Integer loginRes = customerLoginService.login(phone, value);
        if(loginRes==1){
            Member member = new Member();
            member.setPhone(phone);
            Member member1 = userFeignClient.createMember(member);
            HashMap<String, Object> map = new HashMap<>();
            map.put("id",member1.getId());
            map.put("phone",phone);
            String jwt=jwtUtils.generateToken(map);
            result=Result.ok(map);
            result.put("msg","登陆成功！");
            result.put("auth",jwt);
        }else if(loginRes==0) {
            result=Result.error("验证码错误！");
        }else {
            result=Result.error("验证码失效！");
            result.put("code",-1);
        }
        return result;
    }

    //获取验证码
    @GetMapping("getValidateCode")
    public Integer getValidateCode(String phone){
        return customerLoginService.getValidateCode(phone);
    }

    @PostMapping("checkAuth")
    public Result checkAuth(String token){
        Result result = null;
        HashMap<String, Object> map = new HashMap<>();
        if(StringUtils.isBlank(token)){
            result=Result.error("token无效！");
        }else {
            try {
                Claims claim = jwtUtils.getClaimByToken(token);
                map.put("msg","验证成功！");
                map.put("data",claim);
                result=Result.ok(map);
            } catch (ExpiredJwtException e) {
                map.put("msg","凭证过期");
                map.put("code",-1);
                result=Result.ok(map);
            }catch (JwtException e){
                result=Result.error("token无效！");
            }
        }
        System.out.println(result);
        return result;
    }

}
